package com.china08.yxyapi.service.yxweike.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder.Type;
import org.elasticsearch.index.query.RegexpQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder.Field;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.china08.yxyapi.SystemConstant;
import com.china08.yxyapi.entity.db.res.YxyResBookContentsKnoledges;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResWeikeKnow;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResWeikeKnowRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.service.yxweike.YxyWeikeService;
import com.china08.yxyapi.util.YxUserPointsUtilV3;
import com.china08.yxyapi.util.YxyResUtil;

@Service
public class YxyWeikeServiceImpl implements YxyWeikeService {

    @Autowired
    private YxyResWeikeKnowRepository weikeKnowRepository;

    @Autowired
    private YxyResResourceRepository resourceRepository;

    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;

    private static final Logger LOGGER = LoggerFactory.getLogger(YxyWeikeServiceImpl.class);

    @Autowired
    private ElasticsearchTemplate et;

    @Autowired
    private YxyResBookContentsRepository yrbcr;

    @Autowired
    private YxyResUtil yxyResUtil;

    @Autowired
    private YxUserPointsUtilV3 yxUserPointsUtilV3;

    @Override
    public Page<ElasticYxyResResource> findResourceEdu(String stage, String subject, String knwId, String areaId,
            String keyword, Boolean falg, String bookId, String contentId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isEmpty(bookId)) {
            // 学段
            if (StringUtils.isNotBlank(stage) && !StringUtils.equals("all", stage)) {
                TermQueryBuilder builder = new TermQueryBuilder("stage", stage);
                boolQueryBuilder.must(builder);
            }
            // 学科
            if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
                TermQueryBuilder builder = new TermQueryBuilder("weikeSubject", subject);
                boolQueryBuilder.must(builder);
            }

        }

        // 范围--共享到教育云
        TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderScope);

        // 非云校微课
        TermQueryBuilder builderYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderYunRes);

        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);
        // 如果是目录查询
        if (falg) {
            // 目录id为空 说明是第一次进入 按bookId查询
            if (StringUtils.isBlank(contentId)) {
                Assert.notNull(StringUtils.defaultIfBlank(bookId, null), "课本Id不能为空");
                // 根据课本Id拿到所有目录id
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                // 根据目录Id拿到所有的知识点Id
                Set<Integer> set = new HashSet<>();
                List<Integer> list = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    set = new HashSet<>(list1);
                    list = new ArrayList<>(set);
                }
                if (CollectionUtils.isEmpty(list)) {
                    list.add(99999);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
                // 目录不为空 根据目录找到知识点
            } else {
                // List<Integer> list =
                // yxyResBookContentsKnoledgesRepository.findKonwIdBy(contentId);
                List<String> list = yxyResUtil.findTocByTocParent(contentId);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(0000);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
            }

        } else {
            // 知识点
            if (StringUtils.isNotBlank(knwId) && !StringUtils.equals("all", knwId)) {
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knwId);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knwId);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knwId);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
            }
        }

        // 教育云所在区域
        if (StringUtils.isNotBlank(areaId) && !StringUtils.equals("all", areaId)) {
            BoolQueryBuilder areBuilder = new BoolQueryBuilder();
            TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", areaId);
            TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", areaId);
            TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", areaId);
            areBuilder.should(builderprovince);
            areBuilder.should(buildercity);
            areBuilder.should(builderdistrict);
            boolQueryBuilder.must(areBuilder);
        }

        // 审核通过
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatus);
        // 非删除
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);
        // 关键字搜索
        Page<ElasticYxyResResource> pageEs = getPageEs(boolQueryBuilder, keyword, pageable);
        return pageEs;
    }

    @Override
    public Page<ElasticYxyResResource> findResourceSch(String stage, String subject, String knowId, String schoolId,
            String keyword, Boolean falg, String bookId, String contentId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if (StringUtils.isEmpty(bookId)) {
            // 学段
            if (StringUtils.isNotBlank(stage) && !StringUtils.equals("all", stage)) {
                TermQueryBuilder builder = new TermQueryBuilder("stage", stage);
                boolQueryBuilder.must(builder);
            }
            // 学科
            if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
                TermQueryBuilder builder = new TermQueryBuilder("weikeSubject", subject);
                boolQueryBuilder.must(builder);
            }
        }

        // 范围--共享到學校
        BoolQueryBuilder viewScopeOrQuery = new BoolQueryBuilder();
        TermQueryBuilder builderviewScope1 = new TermQueryBuilder("viewScope", 1);
        TermQueryBuilder builderviewScope2 = new TermQueryBuilder("viewScope", 2);
        viewScopeOrQuery.should(builderviewScope1);
        viewScopeOrQuery.should(builderviewScope2);
        boolQueryBuilder.must(viewScopeOrQuery);

        // 非云校微课
        TermQueryBuilder builderYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderYunRes);

        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);

        // 如果是目录查询
        if (falg) {
            // 目录id为空 说明是第一次进入 按bookId查询
            if (StringUtils.isBlank(contentId)) {
                Assert.notNull(StringUtils.defaultIfBlank(bookId, null), "课本Id不能为空");
                // 根据课本Id拿到所有目录id
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                // 根据目录Id拿到所有的知识点Id
                Set<Integer> set = new HashSet<>();
                List<Integer> list = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    set = new HashSet<>(list1);
                    list = new ArrayList<>(set);
                }
                if (CollectionUtils.isEmpty(list)) {
                    list.add(99999);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
            } else {
                // List<Integer> list =
                // yxyResBookContentsKnoledgesRepository.findKonwIdBy(contentId);
                List<String> list = yxyResUtil.findTocByTocParent(contentId);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(0000);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
            }

        } else {
            // 知识点
            if (StringUtils.isNotBlank(knowId) && !StringUtils.equals("all", knowId)) {
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowId);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowId);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowId);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
            }
        }
        // 本校
        if (StringUtils.isNotBlank(schoolId)) {
            TermQueryBuilder builderSchool = new TermQueryBuilder("uploaderSchoolId", schoolId);
            boolQueryBuilder.must(builderSchool);
        }
        // 审核通过
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatus);
        // 非删除
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 关键字搜索
        Page<ElasticYxyResResource> pageEs = getPageEs(boolQueryBuilder, keyword, pageable);
        return pageEs;
    }

    @Override
    public Page<ElasticYxyResResource> findResourceYx(String stage, String subject, String knowId, String keyword,
            Boolean falg, String bookId, String contentId, Integer flag, Integer type, Pageable pageable) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isEmpty(bookId)) {
            // 学段
            if (StringUtils.isNotBlank(stage) && !StringUtils.equals("all", stage)) {
                TermQueryBuilder builder = new TermQueryBuilder("stage", stage);
                boolQueryBuilder.must(builder);
            }
            // 学科
            if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
                TermQueryBuilder builder = new TermQueryBuilder("weikeSubject", subject);
                boolQueryBuilder.must(builder);
            }
        }

        // 范围--刨除是私有的 和在学校展示的
        int[] arr = { 0, 1 };
        TermsQueryBuilder builderViewScop = new TermsQueryBuilder("viewScope", arr);
        boolQueryBuilder.mustNot(builderViewScop);

        // // 云校微课
        // BoolQueryBuilder boolYun = new BoolQueryBuilder();
        // TermQueryBuilder builderisYxYunRes = new
        // TermQueryBuilder("isYxYunRes", 1);
        // boolYun.should(builderisYxYunRes);
        // 或者在云校显示
        TermQueryBuilder builderisviewYun = new TermQueryBuilder("isYxView", 1);
        // boolYun.should(builderisviewYun);
        boolQueryBuilder.must(builderisviewYun);

        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);

        // 如果是目录查询
        if (falg) {
            // 目录id为空 说明是第一次进入 按bookId查询
            if (StringUtils.isBlank(contentId)) {
                Assert.notNull(StringUtils.defaultIfBlank(bookId, null), "课本Id不能为空");
                // 根据课本Id拿到所有目录id
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                // 根据目录Id拿到所有的知识点Id
                Set<Integer> set = new HashSet<>();
                List<Integer> list = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    set = new HashSet<>(list1);
                    list = new ArrayList<>(set);
                }
                if (CollectionUtils.isEmpty(list)) {
                    list.add(99999);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
            } else {
                List<String> list = yxyResUtil.findTocByTocParent(contentId);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(0000);
                }
                // List<Integer> list =
                // yxyResBookContentsKnoledgesRepository.findKonwIdBy(contentId);
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
            }

        } else {
            // 知识点
            if (StringUtils.isNotBlank(knowId) && !StringUtils.equals("all", knowId)) {
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowId);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowId);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowId);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                boolQueryBuilder.must(knoBuilder);
            }
        }

        // 审核通过
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatus);
        // 非删除
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 是否是vip
        // 1.vip
        if (flag == 1) {
            TermQueryBuilder builderIsVip = new TermQueryBuilder("isVip", true);
            boolQueryBuilder.must(builderIsVip);
            // 免费
        } else if (flag == 2) {
            TermQueryBuilder builderIsVip = new TermQueryBuilder("isVip", true);
            boolQueryBuilder.mustNot(builderIsVip);
        }
        // 是否是 精品资源
        if (type == 0) {
            TermQueryBuilder builderJp = new TermQueryBuilder("isHighQualityYx", 1);
            boolQueryBuilder.must(builderJp);
        } else if (type == 1) {
            TermQueryBuilder builderJp = new TermQueryBuilder("isHighQualityYx", 1);
            boolQueryBuilder.mustNot(builderJp);
        }
        // 关键字搜索
        Page<ElasticYxyResResource> pageEs = getPageEs(boolQueryBuilder, keyword, pageable);
        return pageEs;
    }

    private Page<ElasticYxyResResource> getPage(BoolQueryBuilder boolQueryBuilder, Pageable pageable) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(pageable)
                .build();
        Page<ElasticYxyResResource> respPage = et.queryForPage(searchQuery, ElasticYxyResResource.class);
        LOGGER.info(boolQueryBuilder.toString());
        return respPage;
    }

    private Page<ElasticYxyResResource> getPage2(BoolQueryBuilder boolQueryBuilder, String keyword, Pageable pageable) {
        // LOGGER.info("===============" + boolQueryBuilder.toString());
        // 高亮
        SearchQuery searchQuery = null;
        Page<ElasticYxyResResource> respPage = null;

        List<HighlightBuilder.Field> heightFields = new ArrayList<HighlightBuilder.Field>();
        if (StringUtils.isNoneEmpty(keyword)) {
            Field field = new Field("title").preTags("<span style='color:red'>").postTags("</span>").fragmentSize(250);
            heightFields.add(field);
            HighlightBuilder.Field[] stockArr = new HighlightBuilder.Field[heightFields.size()];
            stockArr = heightFields.toArray(stockArr);
            searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withHighlightFields(stockArr)
                    .withPageable(pageable).build();
        } else {
            searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(pageable).build();
        }

        if (CollectionUtils.isNotEmpty(heightFields)) {
            respPage = et.queryForPage(searchQuery, ElasticYxyResResource.class, new SearchResultMapper() {
                @SuppressWarnings("unchecked")
                @Override
                public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
                    long totalHits = response.getHits().totalHits();
                    List<T> chunk = new ArrayList<T>();
                    for (SearchHit searchHit : response.getHits()) {
                        if (response.getHits().getHits().length <= 0) { return null; }
                        Map<String, Object> entityMap = searchHit.getSource();
                        for (HighlightBuilder.Field highName : heightFields) {
                            Text text[];
                            try {
                                text = searchHit.getHighlightFields().get(highName.name()).fragments();
                            } catch (Exception e) {
                                try {
                                    text = searchHit.getHighlightFields().get(highName.name()).fragments();
                                } catch (Exception e1) {
                                    continue;
                                }
                            }
                            if (text.length > 0) {
                                String highValue = searchHit.getHighlightFields().get(highName.name()).fragments()[0]
                                        .toString();
                                entityMap.put(highName.name(), highValue);
                            }
                        }
                        try {
                            chunk.add((T) mapToObject(entityMap, ElasticYxyResResource.class));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return new PageImpl<T>(chunk, pageable, totalHits);
                }
            });
        } else// 如果不设置高亮
        {
            // LOGGER.info("#################" + boolQueryBuilder.toString());
            respPage = et.queryForPage(searchQuery, ElasticYxyResResource.class);
        }

        // 处理结果集
        Page<ElasticYxyResResource> basePage = new PageImpl<ElasticYxyResResource>(respPage.getContent(), pageable,
                respPage.getTotalElements());
        return basePage;
    }

    /**
     * 将map映射成实体类对象
     */
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) return null;
        Object obj = beanClass.newInstance();
        org.apache.commons.beanutils.BeanUtils.populate(obj, map);
        return obj;
    }

    @Override
    public ElasticYxyResResource findOneResource(String weikeid) {
        GetQuery getQuery = new GetQuery();
        getQuery.setId(weikeid);
        ElasticYxyResResource eWeike = et.queryForObject(getQuery, ElasticYxyResResource.class);
        return eWeike;
    }

    @Override
    public Page<ElasticYxyResResource> findMyWeike(String stage, String subject, Integer viewScope, Integer status,
            String keyword, String userId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        // 我的微课
        TermQueryBuilder builderMy = new TermQueryBuilder("uploaderId", userId);
        boolQueryBuilder.must(builderMy);

        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);

        // 学段
        if (StringUtils.isNotBlank(stage) && !StringUtils.equals("all", stage)) {
            TermQueryBuilder builder = new TermQueryBuilder("stage", stage);
            boolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("weikeSubject", subject);
            boolQueryBuilder.must(builder);
        }

        // 共享范围
        if (viewScope != null) {
            TermQueryBuilder builder = new TermQueryBuilder("viewScope", viewScope);
            boolQueryBuilder.must(builder);
        }

        // 审核状态
        if (status != null) {
            TermQueryBuilder builder = new TermQueryBuilder("status", status);
            boolQueryBuilder.must(builder);
        }

        // 未删除
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 关键字搜索
        Page<ElasticYxyResResource> page = getPageEs1(boolQueryBuilder, keyword, pageable);
        return page;
    }

    @Override
    @Transactional
    public void delete(String weikeId) {
        // 删除微课
        YxyResResource resource = resourceRepository.findById(weikeId);
        if (resource != null) {
            resource.setIsDelete(1);
            resourceRepository.save(resource);
        }
        // 删除微课下的知识点
        List<YxyResWeikeKnow> weikeKnows = weikeKnowRepository.findByWeikeId(weikeId);
        for (YxyResWeikeKnow yxyResWeikeKnow : weikeKnows) {
            yxyResWeikeKnow.setWeiKeStatus(0);
            weikeKnowRepository.save(yxyResWeikeKnow);
        }
    }

    @Override
    public List<ElasticYxyResResource> findTop8Resources() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);
        // 教育云的资源
        // TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 2);
        // boolQueryBuilder.must(builderScope);
        // 云校微课
        TermQueryBuilder builderYunRes = new TermQueryBuilder("isYxYunRes", 1);
        boolQueryBuilder.must(builderYunRes);
        // // 上架
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatus);
        // // 未删除
        TermQueryBuilder builderDelete = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDelete);
        // 时间降序排列
        SortBuilder sortBuilder = new FieldSortBuilder("uploadTime").order(SortOrder.DESC);
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(sortBuilder)
                .build();
        List<ElasticYxyResResource> elasticYxyResResourceLst = et.queryForList(searchQuery,
                ElasticYxyResResource.class);
        if (elasticYxyResResourceLst != null && elasticYxyResResourceLst.size() > 8) {
            elasticYxyResResourceLst = elasticYxyResResourceLst.subList(0, 8);
        }
        return elasticYxyResResourceLst;
    }

    @Override
    public List<ElasticYxyResResource> findTop8Resources(String areaId) {
        List<ElasticYxyResResource> elasticYxyResResources = new ArrayList<ElasticYxyResResource>();

        TermQueryBuilder stage01 = new TermQueryBuilder("stage", "01");
        List<ElasticYxyResResource> weiKe01 = findWeiKe(stage01, 4);
        elasticYxyResResources.addAll(weiKe01);
        TermQueryBuilder stage02 = new TermQueryBuilder("stage", "02");
        List<ElasticYxyResResource> weiKe02 = findWeiKe(stage02, 2);
        elasticYxyResResources.addAll(weiKe02);
        TermQueryBuilder stage03 = new TermQueryBuilder("stage", "03");
        List<ElasticYxyResResource> weiKe03 = findWeiKe(stage03, 2);
        elasticYxyResResources.addAll(weiKe03);

        // 2017-08-3注释 改为4个小学2个初中2个高中
        // BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // // 微课类型
        // TermQueryBuilder builderType = new TermQueryBuilder("typeId",
        // "yx14");
        // boolQueryBuilder.must(builderType);
        // // 教育云的资源
        // TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 2);
        // boolQueryBuilder.must(builderScope);
        // // // 上架
        // TermQueryBuilder builderStatus = new TermQueryBuilder("status", 1);
        // boolQueryBuilder.must(builderStatus);
        // // // 未删除
        // TermQueryBuilder builderDelete = new TermQueryBuilder("isDelete", 0);
        // boolQueryBuilder.must(builderDelete);
        // // 区域
        // // 教育云所在区域
        // if (StringUtils.isNotBlank(areaId)) {
        // BoolQueryBuilder areBuilder = new BoolQueryBuilder();
        // TermQueryBuilder builderprovince = new
        // TermQueryBuilder("provinceCode", areaId);
        // TermQueryBuilder buildercity = new TermQueryBuilder("cityCode",
        // areaId);
        // TermQueryBuilder builderdistrict = new
        // TermQueryBuilder("districtCode", areaId);
        // areBuilder.should(builderprovince);
        // areBuilder.should(buildercity);
        // areBuilder.should(builderdistrict);
        // boolQueryBuilder.must(areBuilder);
        // }
        // // 时间降序排列
        // SortBuilder sortBuilder = new
        // FieldSortBuilder("uploadTime").order(SortOrder.DESC);
        // SearchQuery searchQuery = new
        // NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(sortBuilder)
        // .build();
        // List<ElasticYxyResResource> elasticYxyResResourceLst =
        // et.queryForList(searchQuery,
        // ElasticYxyResResource.class);
        //
        // List<ElasticYxyResResource> elasticYxyResResources = new
        // ArrayList<ElasticYxyResResource>();
        // // 区域的够8个
        // if (elasticYxyResResourceLst != null &&
        // elasticYxyResResourceLst.size() > 8) {
        // elasticYxyResResourceLst = elasticYxyResResourceLst.subList(0, 8);
        // elasticYxyResResources.addAll(elasticYxyResResourceLst);
        // }
        // // 区域的不够8个
        // else if (elasticYxyResResourceLst != null &&
        // elasticYxyResResourceLst.size() < 8) {
        // elasticYxyResResources.addAll(elasticYxyResResourceLst);
        // Integer size = 8 - elasticYxyResResourceLst.size();
        //
        // List<String> areaWeikeIds = new ArrayList<String>();
        // for (ElasticYxyResResource elasticYxyResResource :
        // elasticYxyResResources) {
        // areaWeikeIds.add(elasticYxyResResource.getId());
        // }
        // List<ElasticYxyResResource> elasticYxyResResourceLst2 =
        // findTop8Resources(size, areaWeikeIds);
        // elasticYxyResResources.addAll(elasticYxyResResourceLst2);
        //
        // }
        // // 区域的一个都没有时
        // else {
        // List<ElasticYxyResResource> elasticYxyResResourceLst3 =
        // findTop8Resources();
        // elasticYxyResResources.addAll(elasticYxyResResourceLst3);
        // }
        return elasticYxyResResources;
    }

    @Override
    public Page<ElasticYxyResResource> findResourceSchUp(String stage, String subject, String schoolId, Integer status,
            String keyword, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 学段
        if (StringUtils.isNotBlank(stage) && !StringUtils.equals("all", stage)) {
            TermQueryBuilder builder = new TermQueryBuilder("stage", stage);
            boolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("weikeSubject", subject);
            boolQueryBuilder.must(builder);
        }

        // 范围--分享到学校
        TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 1);
        boolQueryBuilder.must(builderScope);

        // 非云校微课
        TermQueryBuilder builderYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderYunRes);

        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);
        // 本校
        if (StringUtils.isNotBlank(schoolId)) {
            TermQueryBuilder builderSchool = new TermQueryBuilder("uploaderSchoolId", schoolId);
            boolQueryBuilder.must(builderSchool);
        }
        // 上架/下架/待审核/审核未通过
        if (status != null) {
            TermQueryBuilder builderStatus = new TermQueryBuilder("status", status);
            boolQueryBuilder.must(builderStatus);
        }
        // 非删除
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 关键字搜索
        Page<ElasticYxyResResource> page = getPageEs1(boolQueryBuilder, keyword, pageable);
        return page;
    }

    @Override
    @Transactional
    public void audit(String weikeId, Integer status, String remark, YxyProfile yxyProfile) {
        YxyResResource resResource = resourceRepository.findById(weikeId);
        if (resResource != null) {
            resResource.setStatus(status);
            if (status == 2 || status == 3) {
                resResource.setRemark(remark);
            }

            // 审核人信息
            resResource.setAuditUserId(yxyProfile.getId());
            resResource.setAuditUserName(yxyProfile.getUserNick());

            // 审核学校信息
            resResource.setAuditSchoolId(yxyProfile.getSchoolId());
            resResource.setAuditSchoolName(yxyProfile.getSchoolName());
            resourceRepository.save(resResource);

            // 上传加积分
            if (status == 1) {
                yxUserPointsUtilV3.uploadResourceVideo(resResource.getUploaderId());
            }
            // 下架扣积分
            if (status == 3) {
                yxUserPointsUtilV3.downResourceVideo(resResource.getUploaderId());
            }
        }
    }

    @Override
    public long auditCountEdu(YxyProfile yxyProfile) {

        // 查询学校所属区域信息
        Boolean isBureau = yxyProfile.getSchoolIsBureau();
        String areaName = "";
        String areaId = "";
        if (isBureau) {
            Integer bureauLevel = yxyProfile.getSchoolBureauLevel();
            if (bureauLevel == 2) {
                areaName = "provinceCode";
                areaId = yxyProfile.getSchoolAreaIdProvince();
            } else if (bureauLevel == 1) {
                areaName = "cityCode";
                areaId = yxyProfile.getSchoolAreaIdCity();
            } else if (bureauLevel == 0) {
                areaName = "districtCode";
                areaId = yxyProfile.getSchoolAreaIdDistrict();
            }
        }

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 所在区域
        if (StringUtils.isNoneBlank(areaName) && StringUtils.isNotBlank(areaId)) {
            TermQueryBuilder builderArea = new TermQueryBuilder(areaName, areaId);
            boolQueryBuilder.must(builderArea);
        }

        // 范围--教育云
        TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderScope);
        // 非云校微课
        TermQueryBuilder builderYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderYunRes);
        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);
        // 待审核
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 0);
        boolQueryBuilder.must(builderStatus);
        // 非删除
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
        long count = et.count(query, ElasticYxyResResource.class);
        return count;
    }

    @Override
    public Page<ElasticYxyResResource> findResourceEduUp(String stage, String subject, YxyProfile yxyProfile,
            Integer status, String keyword, Pageable pageable) {
        // 查询学校所属区域信息
        Boolean isBureau = yxyProfile.getSchoolIsBureau();
        String areaName = "";
        String areaId = "";
        if (isBureau) {
            Integer bureauLevel = yxyProfile.getSchoolBureauLevel();
            if (bureauLevel == 2) {
                areaName = "provinceCode";
                areaId = yxyProfile.getSchoolAreaIdProvince();
            } else if (bureauLevel == 1) {
                areaName = "cityCode";
                areaId = yxyProfile.getSchoolAreaIdCity();
            } else if (bureauLevel == 0) {
                areaName = "districtCode";
                areaId = yxyProfile.getSchoolAreaIdDistrict();
            }
        }

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 学段
        if (StringUtils.isNotBlank(stage) && !StringUtils.equals("all", stage)) {
            TermQueryBuilder builder = new TermQueryBuilder("stage", stage);
            boolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("weikeSubject", subject);
            boolQueryBuilder.must(builder);
        }

        // 范围
        TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderScope);

        // 非云校微课
        TermQueryBuilder builderYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderYunRes);

        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);

        // 所在区域
        if (StringUtils.isNotBlank(areaName) && StringUtils.isNotBlank(areaId)) {
            TermQueryBuilder builderArea = new TermQueryBuilder(areaName, areaId);
            boolQueryBuilder.must(builderArea);
        } else {
            Assert.isTrue(false, "该学校不是教育局");
        }

        // 上架/下架/待审核/审核未通过
        if (status != null) {
            TermQueryBuilder builderStatus = new TermQueryBuilder("status", status);
            boolQueryBuilder.must(builderStatus);
        }
        // 非删除
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 关键字搜索
        Page<ElasticYxyResResource> page = getPageEs1(boolQueryBuilder, keyword, pageable);
        return page;
    }

    @Override
    public long auditCountSch(String schoolId) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 本校
        TermQueryBuilder builderSchool = new TermQueryBuilder("uploaderSchoolId", schoolId);
        boolQueryBuilder.must(builderSchool);
        // 范围--分享到学校
        TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 1);
        boolQueryBuilder.must(builderScope);
        // 非云校微课
        TermQueryBuilder builderYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderYunRes);
        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);
        // 待审核
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 0);
        boolQueryBuilder.must(builderStatus);
        // 非删除
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);
        SearchQuery query = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
        long count = et.count(query, ElasticYxyResResource.class);
        return count;
    }

    @Override
    public List<ElasticYxyResResource> findTop8Resources(Integer size, List<String> areaWeikeIds) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);

        // 教育云的资源---非私有
        TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderScope);

        // 云校微课
        BoolQueryBuilder boolYun = new BoolQueryBuilder();
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 1);
        boolYun.should(builderisYxYunRes);
        // 或者在云校显示
        TermQueryBuilder builderisviewYun = new TermQueryBuilder("isYxView", 1);
        boolYun.should(builderisviewYun);
        boolQueryBuilder.must(boolYun);
        // // 上架
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatus);
        // // 未删除
        TermQueryBuilder builderDelete = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDelete);

        // 排除区域的
        TermsQueryBuilder builderidNot = new TermsQueryBuilder("id", areaWeikeIds);
        boolQueryBuilder.mustNot(builderidNot);
        // 时间降序排列
        SortBuilder sortBuilder = new FieldSortBuilder("uploadTime").order(SortOrder.DESC);
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(sortBuilder)
                .build();
        List<ElasticYxyResResource> elasticYxyResResourceLst = et.queryForList(searchQuery,
                ElasticYxyResResource.class);
        if (elasticYxyResResourceLst != null && elasticYxyResResourceLst.size() > size) {
            elasticYxyResResourceLst = elasticYxyResResourceLst.subList(0, size);
        }
        return elasticYxyResResourceLst;
    }

    private List<ElasticYxyResResource> findWeiKe(TermQueryBuilder phaseTypeBuilder, Integer size) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 微课类型
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.must(builderType);

        // 学段team
        boolQueryBuilder.must(phaseTypeBuilder);

        // 教育云的资源---非私有
        TermQueryBuilder builderScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderScope);

        // 云校微课
        // BoolQueryBuilder boolYun = new BoolQueryBuilder();
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 1);
        boolQueryBuilder.must(builderisYxYunRes);
        // 或者在云校显示
        TermQueryBuilder builderisviewYun = new TermQueryBuilder("isYxView", 1);
        boolQueryBuilder.must(builderisviewYun);
        // boolQueryBuilder.must(boolYun);

        // // 上架
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatus);
        // // 未删除
        TermQueryBuilder builderDelete = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDelete);
        // 时间降序排列
        SortBuilder sortBuilder = new FieldSortBuilder("uploadTime").order(SortOrder.DESC);

        Pageable pageable = new PageRequest(0, size);

        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(sortBuilder)
                .withPageable(pageable).build();
        List<ElasticYxyResResource> elasticYxyResResourceLst = et.queryForList(searchQuery,
                ElasticYxyResResource.class);
        return elasticYxyResResourceLst;
    }

    @Override
    public BoolQueryBuilder keyword(String keyword, Integer type, BoolQueryBuilder builder) {
        if (StringUtils.isNotBlank(keyword) && keyword.length() == 1) {
            RegexpQueryBuilder builderK = new RegexpQueryBuilder("title",
                    SystemConstant.RESOURCE_PREFIX + keyword + SystemConstant.RESOURCE_SUFFIX);
            builder.must(builderK);
        } else {
            if (type == 1) {
                MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", keyword).type(Type.PHRASE);
                builder.must(matchQueryBuilder);
            } else if (type == 2) {
                MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", keyword);
                builder.must(matchQueryBuilder);
            } else if (type == 4) {
                RegexpQueryBuilder matchQueryBuilder = new RegexpQueryBuilder("title",
                        SystemConstant.RESOURCE_PREFIX + keyword + SystemConstant.RESOURCE_SUFFIX);
                builder.must(matchQueryBuilder);
            } else {
                BoolQueryBuilder keywordBoolQueryBuilder = new BoolQueryBuilder();
                char[] key = keyword.toCharArray();
                for (char c : key) {
                    RegexpQueryBuilder builderK = new RegexpQueryBuilder("title",
                            SystemConstant.RESOURCE_PREFIX + c + SystemConstant.RESOURCE_SUFFIX);
                    keywordBoolQueryBuilder.should(builderK);
                }
                builder.must(keywordBoolQueryBuilder);
            }
        }
        return builder;
    }

    /**
     * 高亮的搜索
     */
    @Override
    public Page<ElasticYxyResResource> getPageEs(BoolQueryBuilder maxBoolQueryBuilder, String keyword,
            Pageable pageable) {
        BoolQueryBuilder b1 = new BoolQueryBuilder();
        b1.must(maxBoolQueryBuilder);
        Page<ElasticYxyResResource> page = null;
        if (StringUtils.isNotBlank(keyword)) {
            if (StringUtils.isNotBlank(keyword) && !StringUtils.equals("all", keyword)) {
                b1 = keyword(keyword, 1, b1);
            }
            page = getPage2(b1, keyword, pageable);
            if (page.getContent().size() == 0 && StringUtils.isNotBlank(keyword)) {
                BoolQueryBuilder b2 = new BoolQueryBuilder();
                b2.must(maxBoolQueryBuilder);
                b2 = keyword(keyword, 2, b2);
                page = getPage2(b2, keyword, pageable);
                if (page.getContent().size() == 0) {
                    BoolQueryBuilder b4 = new BoolQueryBuilder();
                    b4.must(maxBoolQueryBuilder);
                    b4 = keyword(keyword, 4, b4);
                    page = getPage2(b4, keyword, pageable);
                    if (page.getContent().size() == 0) {
                        BoolQueryBuilder b3 = new BoolQueryBuilder();
                        b3.must(maxBoolQueryBuilder);
                        b3 = keyword(keyword, 3, b3);
                        page = getPage2(b3, keyword, pageable);
                    }
                }
            }
        } else {
            page = getPage2(b1, keyword, pageable);
        }
        return page;
    }

    @Override
    public Page<ElasticYxyResResource> getPageEs1(BoolQueryBuilder maxBoolQueryBuilder, String keyword,
            Pageable pageable) {
        BoolQueryBuilder b1 = new BoolQueryBuilder();
        b1.must(maxBoolQueryBuilder);
        Page<ElasticYxyResResource> page = null;
        if (StringUtils.isNotBlank(keyword)) {
            if (StringUtils.isNotBlank(keyword) && !StringUtils.equals("all", keyword)) {
                b1 = keyword(keyword, 1, b1);
            }
            page = getPage(b1, pageable);
            if (page.getContent().size() == 0 && StringUtils.isNotBlank(keyword)) {
                BoolQueryBuilder b2 = new BoolQueryBuilder();
                b2.must(maxBoolQueryBuilder);
                b2 = keyword(keyword, 2, b2);
                SearchQuery query2 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b2).build();
                page = et.queryForPage(query2, ElasticYxyResResource.class);
                if (page.getContent().size() == 0) {
                    BoolQueryBuilder b4 = new BoolQueryBuilder();
                    b4.must(maxBoolQueryBuilder);
                    b4 = keyword(keyword, 4, b4);
                    SearchQuery query4 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b4).build();
                    page = et.queryForPage(query4, ElasticYxyResResource.class);
                    if (page.getContent().size() == 0) {
                        BoolQueryBuilder b3 = new BoolQueryBuilder();
                        b3.must(maxBoolQueryBuilder);
                        b3 = keyword(keyword, 3, b3);
                        SearchQuery query3 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b3)
                                .build();
                        page = et.queryForPage(query3, ElasticYxyResResource.class);
                    }
                }
            }
        } else {
            page = getPage(b1, pageable);
        }
        return page;
    }
}
